﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using QuickGet.Core.Models;

namespace QuickGet.Core.Stores
{
    public abstract class PackageStoreBase : IPackageStore
    {
        protected readonly IOptions<QuickGetOptions> _options;
        protected readonly ILogger _logger;
        protected const string packageFileNameFormat = "{0}.{1}.nupkg";

        public PackageStoreBase(ILogger logger, IOptions<QuickGetOptions> options)
        {
            _logger = logger;
            _options = options;
        }

        public abstract Task<List<PackageVersionInfo>> GetDownloadedVersionsAsync(string packageId, CancellationToken cancellationToken);
        public abstract Task<string?> GetPackageDownloadPathAsync(string packageId, string version, CancellationToken cancellationToken);
        public abstract Task SaveAsync(string packageId, CancellationToken cancellationToken);
        public abstract Task SaveDownloadAsync(string packageId, string version, string path, CancellationToken cancellationToken);
        public abstract Task<List<PackageInfo>> GetListAsync(CancellationToken cancellationToken);

        public virtual string BuildPackageSavePath(string packageId, string version)
            => Path.Combine(
                AppContext.BaseDirectory,
                _options.Value.StoragePath,
                NormalizePackageId(packageId),
                NormalizePackageVersion(version));

        public virtual string NormalizePackageId(string packageId) => packageId.ToLowerInvariant();
        public virtual string NormalizePackageVersion(string version) => version.ToLowerInvariant();

        public string GetPackageFileName(string packageId, string version)
            => string.Format(packageFileNameFormat, NormalizePackageId(packageId), NormalizePackageVersion(version));
    }
}
